package com.c5c7.servlet;

import com.c5c7.bean.NewsBean;
import com.c5c7.dao.NewsDao;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * 1. 接收post网址 /newsAdd.jsp
 * 2. 接收到传递过来的新闻参数 新闻标题 新闻内容
 * 3。 完成新闻的添加
 * 4. 跳转到其他页面
 */

@WebServlet("/newsEdit.jsp")
public class NewsUpdateServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String user = (String) req.getSession().getAttribute("User"); // 获取会话
        if (user == null || user.equals("")) {
            resp.sendRedirect("login.jsp");
            return;
        }
        String newsTitle = req.getParameter("upd_NewsTitle");
        String newsContent = req.getParameter("upd_NewsContent");
        int newsId = Integer.parseInt(req.getParameter("newsId"));
        NewsBean newsBean = new NewsBean();
        newsBean.setNewsID(newsId);
        newsBean.setNewsTitle(newsTitle);
        newsBean.setNewsContent(newsContent);
        newsBean.setAdminName(user);
        NewsDao newsDao = new NewsDao();
        int result = newsDao.update(newsBean);
        if (result > 0) {
            resp.sendRedirect("news.jsp");
        }else {
            req.setAttribute("msg","更新失败");
            req.setAttribute("url","news.jsp");
            req.getRequestDispatcher("WEB-INF/error.jsp").forward(req, resp);
        }

    }
}
